package main

import (
	"fmt"
	"log"
	"net/http"

	"golang.org/x/net/websocket"
)

func reciveMsg(ws *websocket.Conn, userID string) {
	msg := make([]byte, 512)
	for {
		n, err := ws.Read(msg)
		if err != nil {
			fmt.Println("error:", err.Error(), userID, "is offline")
			return
		}
		fmt.Printf("Receive: %s\n", msg[:n])

		//send_msg := "[" + string(msg[:n]) + "]"
		//m, err := ws.Write([]byte(send_msg))
		//if err != nil {
		//	log.Fatal(err)
		//}
		//fmt.Printf("Send: %s\n", msg[:m])
	}
}
func echoHandler(ws *websocket.Conn) {
	req := ws.Request()
	err := req.ParseForm()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(req.Form)
	fmt.Println(req)
	userID := req.Form["userID"][0]
	if userID == "" {
		fmt.Println("userID is empty!")
		ws.Close()
		return
	}
	msg := make([]byte, 512)
	go reciveMsg(ws, userID)
	for i := 0; i < 10; {
		n, err := fmt.Scan(&msg)
		if err != nil {
			fmt.Println("error:", err.Error(), userID, "is offline")
			return
		}
		if n == 0 {
			fmt.Println("error:no input")
			continue
		}
		i++
		n, err = ws.Write(msg)
		if err != nil {
			fmt.Println("error:", err.Error(), userID, "is offline")
			return
		}
		fmt.Printf("Send: %s\n", msg[:n])
	}
	_, err = ws.Write(nil)
	if err != nil {
		fmt.Println("error:", err.Error(), userID, "is offline")
		return
	}
}

func main() {
	http.Handle("/echo", websocket.Handler(echoHandler))
	http.Handle("/", http.FileServer(http.Dir(".")))

	err := http.ListenAndServe(":8080", nil)

	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
